package com.chookss.home.audit.shop;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.adapter.FilesAdapter;
import com.chookss.home.audit.clockIn.ClockInUtils;
import com.chookss.home.audit.service.UploadShopService;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.entity.ClockInGroupEntity;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.home.entity.ReimbursementTypeEntity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.filePicker.FilePicker;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.util.Const;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.BasisTimesUtils;
import com.chookss.view.DrawableTextView;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.LogBottomDialog;
import com.chookss.view.RoundCornerImageView;
import com.chookss.view.listener.HomeBottomDialogListener;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopAddActivity extends BaseAct {
    //新建 及修改物品
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvPeople)
    TextView tvPeople;
    @BindView(R.id.tvType)
    DrawableTextView tvType;
    @BindView(R.id.tvGroup)
    DrawableTextView tvGroup;
    @BindView(R.id.edName)
    EditText edName;
    @BindView(R.id.edMoney)
    EditText edMoney;
    @BindView(R.id.edNum)
    EditText edNum;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.fileRcv)
    RecyclerView fileRcv;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.llGroup)
    LinearLayout llGroup;
    @BindView(R.id.groupEmpty)
    View groupEmpty;
    @BindView(R.id.rlSubtract)
    RelativeLayout rlSubtract;
    @BindView(R.id.ivSubtract)
    ImageView ivSubtract;
    @BindView(R.id.rlAdd)
    RelativeLayout rlAdd;
    @BindView(R.id.ivAdd)
    ImageView ivAdd;
    @BindView(R.id.tvDepartment)
    TextView tvDepartment;
    @BindView(R.id.ivShopAdd)
    ImageView ivShopAdd;
    @BindView(R.id.ivShopCover)
    RoundCornerImageView ivShopCover;
    @BindView(R.id.ivShopDelete)
    ImageView ivShopDelete;
    @BindView(R.id.llHouse)
    LinearLayout llHouse;
    @BindView(R.id.llNormalShop)
    LinearLayout llNormalShop;
    @BindView(R.id.edHouseMoney)
    EditText edHouseMoney;
    @BindView(R.id.edPledgeMoney)
    EditText edPledgeMoney;
    @BindView(R.id.tvRentTime)
    DrawableTextView tvRentTime;
    @BindView(R.id.tvRentEndTime)
    DrawableTextView tvRentEndTime;
    @BindView(R.id.tvPayType)
    DrawableTextView tvPayType;
    private static final int REQUEST_CODE_CHOOSE = 23;
    private ReimbursementDetailEntity reimbursementDetailEntity = null;
    private List<ReimbursementTypeEntity> reimbursementTypeEntities = new ArrayList<>();
    private List<ClockInGroupEntity> groupEntities = new ArrayList<>();
    //报销  物料  借款公用一个实体类
    private List<ReimbursementDetailEntity.AnnexsBean> filesList = new ArrayList<>();
    private FilesAdapter adapter;
    private String[] groupArray = null;
    private String[] shopArray = null;
    private String[] payArray = null;
    private String goodsCode = "", id = "";//不为空说明是修改进来的
    private String groupCode = "", groupName = "", shopTypeCode = "";
    private boolean errorStatus = false;//true 说明是上传失败进来
    private String tag = "ShopAddActivity_DownloadFile";//下载文件打的标签
    private LogBottomDialog bottomDialog = null;
    private String imageUrl = "";//物品封面
    private String workflowId = "";//物品修改所用
    private String orgCode = "", orgName = "";//所属部门
    private boolean isProjectManager = false;//是否项目管理过来新增物料的
    private int payType = -1;//租房支付方式
    private boolean rentLease = false;//是否是房屋租赁

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_shop);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        goodsCode = getIntent().getStringExtra("goodsCode");
        id = getIntent().getStringExtra("id");
        errorStatus = getIntent().getBooleanExtra("errorStatus", false);
        isProjectManager = getIntent().getBooleanExtra("isProjectManager", false);
        if (isProjectManager) {
            groupCode = getIntent().getStringExtra("groupCode");
            groupName = getIntent().getStringExtra("groupName");
            tvGroup.setText(groupName + "(" + ClockInUtils.getGroupEnd(groupCode) + ")");
            tvGroup.setCompoundDrawables(null, null, null, null);
            groupEmpty.setVisibility(View.VISIBLE);
            llGroup.setVisibility(View.VISIBLE);
        }
        payArray = new String[]{"月付", "季付", "年付"};
        tvPeople.setText(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        fileRcv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new FilesAdapter(R.layout.item_files_list, this, filesList, 0, tag);
        fileRcv.setAdapter(adapter);
        orgCode = new ShareUtils().getString(this, StaticClass.BELG_ORG_CODE, "");
        orgName = new ShareUtils().getString(this, StaticClass.BELG_ORG_NAME, "");
        tvDepartment.setText(orgName);
        if (errorStatus) {
            //上传失败进来的
            reimbursementDetailEntity = (ReimbursementDetailEntity) getIntent().getSerializableExtra("data");
            tvSure.setText("重新提交");
            tvTitle.setText(reimbursementDetailEntity.getProjectName());
            setErrorData();
        } else {
            tvTitle.setText(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + "的物品申请");
            reimbursementDetailEntity = new ReimbursementDetailEntity();
            List<ReimbursementDetailEntity.AnnexsBean> annexsBeanList = new ArrayList<>();
            reimbursementDetailEntity.setAnnexs(annexsBeanList);
        }
        edNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!Utils.isNull(s.toString())) {
                    if (s.toString().equals("1")) {
                        ivSubtract.setBackgroundResource(R.drawable.icount_jian_unsel);
                        rlSubtract.setBackgroundResource(R.drawable.add_shop_subtrat_black_bg);
                    } else {
                        ivSubtract.setBackgroundResource(R.drawable.icount_white_jian);
                        rlSubtract.setBackgroundResource(R.drawable.add_shop_subtrat_red_bg);
                    }
                }
            }
        });
        getGroupList();
        getShopTypeList();
        if (!Utils.isNull(goodsCode)) {
            selectDeail();
            tvSure.setText("重新提交");
            registerBoradcastReceiver();
        }
    }

    private void setErrorData() {
        //上传失败后数据的初始化
        if (reimbursementDetailEntity != null) {
            ivShopCover.setVisibility(View.VISIBLE);
            ivShopDelete.setVisibility(View.VISIBLE);
            ivShopAdd.setVisibility(View.GONE);
            imageUrl = reimbursementDetailEntity.getImageLocUrl();
            Glide.with(ShopAddActivity.this).load(reimbursementDetailEntity.getImageLocUrl()).into(ivShopCover);
            shopTypeCode = reimbursementDetailEntity.getBaoixaoTypeCode();
            tvType.setText(reimbursementDetailEntity.getBaoxiaoTypeName());
            edName.setText(reimbursementDetailEntity.getGoodsName());
            edNum.setText(reimbursementDetailEntity.getGoodsNum());
            edMoney.setText(reimbursementDetailEntity.getAmt());
            groupCode = reimbursementDetailEntity.getGroupCode();
            groupName = reimbursementDetailEntity.getGroupName();
            if (!Utils.isNull(reimbursementDetailEntity.getOrgName())) {
                tvDepartment.setText(reimbursementDetailEntity.getOrgName());
                orgCode = reimbursementDetailEntity.getOrgCode();
                orgName = reimbursementDetailEntity.getOrgName();
            }
            if (!Utils.isNull(reimbursementDetailEntity.getGroupCode())) {
                tvGroup.setText(reimbursementDetailEntity.getGroupName() + "(" + ClockInUtils.getGroupEnd(reimbursementDetailEntity.getGroupCode()) + ")");
                groupEmpty.setVisibility(View.VISIBLE);
                llGroup.setVisibility(View.VISIBLE);
            }

            if (Utils.isNull(reimbursementDetailEntity.getRemark())) {
                edContent.setText("无");
            } else {
                edContent.setText(reimbursementDetailEntity.getRemark());
            }
            filesList.clear();
            filesList.addAll(reimbursementDetailEntity.getAnnexs());
            adapter.notifyDataSetChanged();
            getShopNameList(true);
        }
    }

    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInGroupEntity>>>() {
        }.getType(), null, Urls.selectMyItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInGroupEntity>>() {
            @Override
            public void onSuccess(List<ClockInGroupEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvType == null) {
                        return;
                    }
                    groupEntities.addAll(data);
                    groupArray = new String[groupEntities.size()];
                    for (int i = 0; i < groupEntities.size(); i++) {
                        if ("1".equals(groupEntities.get(i).getMainCd())) {
                            groupArray[i] = groupEntities.get(i).getGroupName() + "[常驻]";
                        } else {
                            groupArray[i] = groupEntities.get(i).getGroupName();
                        }

                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getShopTypeList() {
        //获取物品类型列表
        Map<String, String> map = new HashMap<>();
        map.put("type", "3");//(1-报销 2-借款 3物品
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<ReimbursementTypeEntity>>>() {
        }.getType(), null, Urls.selectBaoxiaoTypeList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ReimbursementTypeEntity>>() {
            @Override
            public void onSuccess(List<ReimbursementTypeEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvType == null) {
                        return;
                    }
                    reimbursementTypeEntities.clear();
                    reimbursementTypeEntities.addAll(data);
                    shopArray = new String[reimbursementTypeEntities.size()];
                    for (int i = 0; i < reimbursementTypeEntities.size(); i++) {
                        shopArray[i] = reimbursementTypeEntities.get(i).getBaoixaoTypeName();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getShopNameList(boolean isEdit) {
        //获取物品名称列表
        Map<String, String> map = new HashMap<>();
        map.put("baoixaoTypeCode", shopTypeCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<ReimbursementTypeEntity>>() {
        }.getType(), null, Urls.selectBaoxiaoInfDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementTypeEntity>() {
            @Override
            public void onSuccess(ReimbursementTypeEntity data) {
                if (tvType == null) {
                    return;
                }
                if (isEdit) {
                    //修改或者本地缓存数据 需要设置一下是否需要附件
                    for (int i = 0; i < data.getAnnexs().size(); i++) {
                        filesList.get(i).setNeedCd(data.getAnnexs().get(i).getNeedCd());
                    }
                } else {
                    reimbursementDetailEntity.getAnnexs().clear();
                    filesList.clear();
                    for (int i = 0; i < data.getAnnexs().size(); i++) {
                        ReimbursementDetailEntity.AnnexsBean annexsBean = new ReimbursementDetailEntity.AnnexsBean();
                        annexsBean.setAnnexName(data.getAnnexs().get(i).getAnnexName());
                        annexsBean.setBaoixaoTypeCode(shopTypeCode);
                        annexsBean.setNeedCd(data.getAnnexs().get(i).getNeedCd());
                        List<ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean> list = new ArrayList<>();
                        annexsBean.setPictureInfoList(list);
                        List<ReimbursementDetailEntity.AnnexsBean.DatabaseBean> list2 = new ArrayList<>();
                        annexsBean.setDatabase(list2);
                        reimbursementDetailEntity.getAnnexs().add(annexsBean);
                    }
                    filesList.addAll(reimbursementDetailEntity.getAnnexs());
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void selectDeail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", goodsCode);
        map.put("type", "8");//3补卡 4请假5外勤6图文7报销
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ReimbursementDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ReimbursementDetailEntity>() {
            @Override
            public void onSuccess(ReimbursementDetailEntity data) {
                if (data != null) {
                    if (tvType == null) {
                        return;
                    }
                    groupCode = data.getGroupCode();
                    workflowId = data.getWorkflowId();
                    groupName = data.getGroupName();
                    shopTypeCode = data.getBaoixaoTypeCode();
                    tvType.setText(data.getBaoixaoTypeName());
                    edName.setText(data.getGoodsName());

                    if (shopTypeCode.equals("BAOX202001010001")) {
                        rentLease = true;
                        llNormalShop.setVisibility(View.GONE);
                        llHouse.setVisibility(View.VISIBLE);
                        edHouseMoney.setText(data.getRant());
                        edPledgeMoney.setText(data.getYajin());
                        tvRentTime.setText(data.getRantStartTime());
                        tvRentEndTime.setText(data.getRantEndTime());
                        tvPayType.setText(data.getAmt());
                        payType = Utils.changeNumber(data.getPayType());
                        if (payType == 1) {
                            tvPayType.setText("月付");
                        } else if (payType == 2) {
                            tvPayType.setText("季付");
                        } else if (payType == 3) {
                            tvPayType.setText("年付");
                        }
                    } else {
                        rentLease = false;
                        llNormalShop.setVisibility(View.VISIBLE);
                        llHouse.setVisibility(View.GONE);
                        edNum.setText(data.getGoodsNum());
                        edMoney.setText(data.getAmt());
                    }
                    if (!Utils.isNull(data.getOrgName())) {
                        tvDepartment.setText(data.getOrgName());
                        orgCode = data.getOrgCode();
                        orgName = data.getOrgName();
                    }
                    if (!Utils.isNull(data.getGroupCode())) {
                        tvGroup.setText(data.getGroupName() + "(" + ClockInUtils.getGroupEnd(data.getGroupCode()) + ")");
                        groupEmpty.setVisibility(View.VISIBLE);
                        llGroup.setVisibility(View.VISIBLE);
                    }
                    if (!Utils.isNull(data.getImageUrl())) {
                        imageUrl = data.getImageUrl();
                        ivShopCover.setVisibility(View.VISIBLE);
                        ivShopDelete.setVisibility(View.VISIBLE);
                        ivShopAdd.setVisibility(View.GONE);
                        Glide.with(ShopAddActivity.this).load(data.getImageUrl()).into(ivShopCover);
                    }
                    edMoney.setText(ClearMoreZeroUtil.subZeroAndDot(data.getAmt()));
                    if (Utils.isNull(data.getRemark())) {
                        edContent.setText("无");
                    } else {
                        edContent.setText(data.getRemark());
                    }
                    filesList.clear();
                    filesList.addAll(data.getAnnexs());
                    adapter.notifyDataSetChanged();
                    getShopNameList(true);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (bottomDialog != null) {
            bottomDialog.dismiss();
        }
    }

    private void requestCamera(int type, int fileNum) {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            if (type == 0 || type == -1) {
                                //选图片
                                PictureSelector.create(ShopAddActivity.this)
                                        .openGallery(SelectMimeType.ofImage())
                                        .isDisplayCamera(true)//是否显示相机入口
                                        .setMaxSelectNum(9 - fileNum)
                                        .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                                        .isPreviewImage(true)//是否支持预览图片
                                        .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                                        .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                                        .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                        .forResult(PictureConfig.CHOOSE_REQUEST + type);
                            } else {
                                //选文档
                                FilePicker
                                        .from(ShopAddActivity.this)
                                        .chooseForMimeType()
                                        .setMaxCount(9 - fileNum)
                                        .setFileTypes("pdf", "doc", "ppt", "xls")
                                        .requestCode(REQUEST_CODE_CHOOSE)
                                        .start();
                            }

                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(ShopAddActivity.this, denied, quick);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST || requestCode == PictureConfig.CHOOSE_REQUEST - 1) {
                // 如果是直接从相册获取
                if (tvType == null) {
                    return;
                }
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());
                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }
                    if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                        //附件选择图片
                        if (parentNum >= 0) {
                            ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean pictureInfoListBean = new ReimbursementDetailEntity.AnnexsBean.PictureInfoListBean();
                            pictureInfoListBean.setPictureUrl(url);
                            pictureInfoListBean.setLocPictureUrl(url);
                            pictureInfoListBean.setAnnexName(filesList.get(parentNum).getAnnexName());
                            pictureInfoListBean.setBaoixaoTypeCode(shopTypeCode);
                            filesList.get(parentNum).getPictureInfoList().add(pictureInfoListBean);
                        }
                    } else {
                        //封面选择最多一张
                        imageUrl = url;
                        ivShopCover.setVisibility(View.VISIBLE);
                        ivShopDelete.setVisibility(View.VISIBLE);
                        ivShopAdd.setVisibility(View.GONE);
                        Glide.with(ShopAddActivity.this).load(imageUrl).into(ivShopCover);

                    }


                }
                if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                    if (filesList.get(parentNum).getPictureInfoList().size() > 0) {
                        adapter.notifyItemChanged(parentNum);
                    }
                }
            }
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //文档选择
                ArrayList<EssFile> essFileList = data.getParcelableArrayListExtra(Const.EXTRA_RESULT_SELECTION);
                if (essFileList.size() != 0) {
                    for (int i = 0; i < essFileList.size(); i++) {
                        ReimbursementDetailEntity.AnnexsBean.DatabaseBean docunmentEntity = new ReimbursementDetailEntity.AnnexsBean.DatabaseBean();
                        docunmentEntity.setDataTitle(essFileList.get(i).getName());
                        docunmentEntity.setDataCode("");
                        docunmentEntity.setDataPath(essFileList.get(i).getAbsolutePath());
                        docunmentEntity.setUploadTime(FileUtils.getDateTime(essFileList.get(i).getAbsolutePath()));
                        docunmentEntity.setDataSize(FileSizeUtil.getAutoFileOrFilesSize((essFileList.get(i).getFile())));
                        docunmentEntity.setAnnexName(filesList.get(parentNum).getAnnexName());
                        docunmentEntity.setBaoixaoTypeCode(shopTypeCode);
                        KLog.i(essFileList.get(i).getAbsolutePath());
                        filesList.get(parentNum).getDatabase().add(docunmentEntity);
                    }

                } else {
                    KLog.i("essFileList.size() == 0");
                }
                if (filesList.get(parentNum).getDatabase().size() > 0) {
                    adapter.notifyItemChanged(parentNum);
                }
            }
        }

    }

    private void uploadData() {
        Intent intent = new Intent(this, UploadShopService.class);
        reimbursementDetailEntity.setProjectName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + "的" + tvType.getText().toString() + "物品申请");
        reimbursementDetailEntity.setGroupCode(groupCode);
        reimbursementDetailEntity.setGroupName(groupName);
        if (rentLease) {
            //房屋租赁
            reimbursementDetailEntity.setRant(edHouseMoney.getText().toString());
            reimbursementDetailEntity.setYajin(edPledgeMoney.getText().toString());
            reimbursementDetailEntity.setRantStartTime(tvRentTime.getText().toString());
            reimbursementDetailEntity.setRantEndTime(tvRentEndTime.getText().toString());
            reimbursementDetailEntity.setPayType(payType + "");
        } else {
            reimbursementDetailEntity.setAmt(edMoney.getText().toString());
            reimbursementDetailEntity.setGoodsNum(edNum.getText().toString());
        }
        reimbursementDetailEntity.setBaoixaoTypeCode(shopTypeCode);
        reimbursementDetailEntity.setBaoxiaoTypeName(tvType.getText().toString());
        reimbursementDetailEntity.setGoodsName(edName.getText().toString());
        reimbursementDetailEntity.setRemark(edContent.getText().toString());
        reimbursementDetailEntity.setGoodsCode(goodsCode);
        reimbursementDetailEntity.setImageLocUrl(imageUrl);
        reimbursementDetailEntity.setImageUrl(imageUrl);
        reimbursementDetailEntity.setOrgCode(orgCode);
        reimbursementDetailEntity.setOrgName(orgName);
        reimbursementDetailEntity.setId(id);
        reimbursementDetailEntity.setWorkflowId(workflowId);
        reimbursementDetailEntity.setOrgCode(new ShareUtils().getString(this, StaticClass.BELG_ORG_CODE, ""));
        reimbursementDetailEntity.setCreateTime(Utils.getCurrentTime2());
        reimbursementDetailEntity.setEmployeeCode(new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        reimbursementDetailEntity.setEmployeeName(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        reimbursementDetailEntity.setCache(System.currentTimeMillis() + "");
        reimbursementDetailEntity.setCacheStatus(0);
        reimbursementDetailEntity.getAnnexs().clear();
        reimbursementDetailEntity.getAnnexs().addAll(filesList);
        intent.putExtra("reimbursementDetailEntity", reimbursementDetailEntity);
        intent.putExtra("cacheStatus", 0);
        startService(intent);
        finish();
    }


    int fileNum = 0;
    int parentNum = -1;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("Files_choice_parent_num")) {
                parentNum = Utils.changeNumber(map.get("Files_choice_parent_num"));
                try {
                    fileNum = filesList.get(parentNum).getPictureInfoList().size() + filesList.get(parentNum).getDatabase().size();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (fileNum >= 9) {
                    MyToast.show("附件最多上传9个");
                    return;
                }
                if (filesList.size() > parentNum) {
                    if (bottomDialog != null) {
                        bottomDialog.dismiss();
                    }
                    bottomDialog = new LogBottomDialog(this, false, new HomeBottomDialogListener() {
                        @Override
                        public void onListItemClick(int position) {
                            if (position == 0) {
                                requestCamera(0, fileNum);
                            } else if (position == 2) {
                                requestCamera(2, fileNum);
                            }
                        }
                    });
                    bottomDialog.show();
                }
            } else if (map.containsKey("deleteReimbursementPic")) {
                int position = Utils.changeNumber(map.get("position"));
                int parent_position = Utils.changeNumber(map.get("parent_position"));
                if (parent_position >= 0 && position >= 0) {
                    FileUtilss.delFile(filesList.get(parent_position).getPictureInfoList().get(position).getLocPictureUrl());
                    filesList.get(parent_position).getPictureInfoList().remove(position);
                    adapter.notifyItemChanged(parent_position);
                }
            }
            if (map.containsKey("deleteReimbursementDocunment")) {
                int position = Utils.changeNumber(map.get("position"));
                int parent_position = Utils.changeNumber(map.get("parent_position"));
                if (parent_position >= 0 && position >= 0) {
                    filesList.get(parent_position).getDatabase().remove(position);
                    adapter.notifyItemChanged(parent_position);
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.tvRentTime, R.id.tvRentEndTime, R.id.tvPayType, R.id.rlSubtract, R.id.rlAdd, R.id.tvType, R.id.tvGroup, R.id.tvSure, R.id.ivShopDelete, R.id.ivShopAdd})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvRentTime:
                showDatePickStartDialog();
                break;
            case R.id.tvRentEndTime:
                showDatePickEndDialog();
                break;
            case R.id.tvPayType:
                new XPopup.Builder(ShopAddActivity.this)
                        .maxWidth(Utils.dip2px(ShopAddActivity.this, 260))
                        .maxHeight(Utils.dip2px(ShopAddActivity.this, 300))
                        .asCenterList("请选择支付方式", payArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        payType = position + 1;
                                        tvPayType.setText(text);
                                    }
                                })
                        .show();
                break;
            case R.id.tvType:
                if (shopArray == null || reimbursementTypeEntities.size() == 0) {
                    MyToast.show("物品类型为空，请联系管理员配置");
                    return;
                }
                new XPopup.Builder(ShopAddActivity.this)
                        .maxWidth(Utils.dip2px(ShopAddActivity.this, 260))
                        .maxHeight(Utils.dip2px(ShopAddActivity.this, 300))
                        .asCenterList("请选择物品类型", shopArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        shopTypeCode = reimbursementTypeEntities.get(position).getBaoixaoTypeCode();
                                        tvType.setText(text);
                                        if (shopTypeCode.equals("BAOX202001010001")) {
                                            rentLease = true;
                                            llNormalShop.setVisibility(View.GONE);
                                            llHouse.setVisibility(View.VISIBLE);
                                        } else {
                                            rentLease = false;
                                            llNormalShop.setVisibility(View.VISIBLE);
                                            llHouse.setVisibility(View.GONE);
                                        }
                                        getShopNameList(false);
                                        if (!isProjectManager) {
                                            if ("1".equals(reimbursementTypeEntities.get(position).getNeedGroupCd())) {
                                                groupCode = "";
                                                groupName = "";
                                                tvGroup.setText("");
                                                groupEmpty.setVisibility(View.VISIBLE);
                                                llGroup.setVisibility(View.VISIBLE);
                                            } else {
                                                groupCode = "";
                                                groupName = "";
                                                groupEmpty.setVisibility(View.GONE);
                                                llGroup.setVisibility(View.GONE);
                                            }
                                        }
                                    }
                                })
                        .show();
                break;
            case R.id.tvGroup:
                if (isProjectManager) {
                    return;
                }
                if (groupArray == null) {
                    MyToast.show("无可选项目组，请联系管理员配置");
                    return;
                }
                new XPopup.Builder(ShopAddActivity.this)
                        .maxWidth(Utils.dip2px(ShopAddActivity.this, 260))
                        .maxHeight(Utils.dip2px(ShopAddActivity.this, 300))
                        .asCenterList("请选择项目组", groupArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        groupCode = groupEntities.get(position).getGroupCode();
                                        groupName = groupEntities.get(position).getGroupName();
                                        tvGroup.setText(text.replace("[常驻]", "") + "(" + ClockInUtils.getGroupEnd(groupEntities.get(position).getGroupCode()) + ")");
                                    }
                                })
                        .show();
                break;
            case R.id.rlSubtract:
                int shopNum = Utils.changeNumber(ClearMoreZeroUtil.subZeroAndDot(edNum.getText().toString())) - 1;
                if (shopNum == 0) {
                    MyToast.show("最小数量是1个");
                    return;
                } else {
                    edNum.setText(shopNum + "");
                }
                try {
                    if (!Utils.isNull(edNum.getText().toString())) {
                        edNum.setSelection(edNum.getText().toString().length());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.rlAdd:
                edNum.setText((Utils.changeNumber(ClearMoreZeroUtil.subZeroAndDot(edNum.getText().toString())) + 1) + "");
                try {
                    if (!Utils.isNull(edNum.getText().toString())) {
                        edNum.setSelection(edNum.getText().toString().length());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.ivShopDelete:
                imageUrl = "";
                ivShopCover.setVisibility(View.GONE);
                ivShopDelete.setVisibility(View.GONE);
                ivShopAdd.setVisibility(View.VISIBLE);
                break;
            case R.id.ivShopAdd:
                requestCamera(-1, 8);
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (Utils.isNull(tvType.getText().toString())) {
                    MyToast.show("请选择物品类型");
                    return;
                }
                if (Utils.isNull(edName.getText().toString())) {
                    MyToast.show("请输入物品名称");
                    return;
                }
                if (rentLease) {
                    if (Utils.isNull(edHouseMoney.getText().toString())) {
                        MyToast.show("请输入月租金");
                        return;
                    }
                    if (Utils.isNull(edPledgeMoney.getText().toString())) {
                        MyToast.show("请输入押金");
                        return;
                    }
                    if (Utils.isNull(tvRentTime.getText().toString())) {
                        MyToast.show("请选择租用起始日期");
                        return;
                    }
                    if (Utils.isNull(tvRentEndTime.getText().toString())) {
                        MyToast.show("请选择租用结束日期");
                        return;
                    }
                    if (Utils.isNull(tvPayType.getText().toString())) {
                        MyToast.show("请选择支付方式");
                        return;
                    }
                } else {
                    if (Utils.isNull(edMoney.getText().toString())) {
                        MyToast.show("请输入物品单价");
                        return;
                    }
                    if (edNum.getText().toString().startsWith("0")) {
                        MyToast.show("物品数量输入异常");
                        return;
                    }
                }

                if (llGroup.getVisibility() == View.VISIBLE) {
                    if (Utils.isNull(tvGroup.getText().toString())) {
                        MyToast.show("请选择项目组");
                        return;
                    }
                }
                if (Utils.isNull(edContent.getText().toString())) {
                    MyToast.show("请输入物品说明");
                    return;
                }
                if (Utils.isNull(imageUrl)) {
                    MyToast.show("请上传物品图片");
                    return;
                }
                int allSize = 0;
                for (int i = 0; i < filesList.size(); i++) {
                    int fileSize = filesList.get(i).getDatabase().size() + filesList.get(i).getPictureInfoList().size();
                    allSize = allSize + fileSize;
                    if (filesList.get(i).getNeedCd().equals("1")) {
                        //1必传
                        if (fileSize == 0) {
                            MyToast.show("请选择" + filesList.get(i).getAnnexName() + "必须的附件");
                            return;
                        }
                    }
                }
                uploadData();
                break;
        }
    }

    int mYear = 0, mMonth = 0, mDay = 0;
    String dayS = "", monthS = "";

    private void showDatePickStartDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mDay == 0) {
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择日期", mYear, mMonth, mDay,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear = year;
                        mMonth = month - 1;
                        mDay = dayOfMonth;
                        if (dayOfMonth > 9) {
                            dayS = dayOfMonth + "";
                        } else {
                            dayS = "0" + dayOfMonth;
                        }
                        if (month > 9) {
                            monthS = month + "";
                        } else {
                            monthS = "0" + month;
                        }
                        if (!Utils.isNull(tvRentEndTime.getText().toString())) {
                            if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                    mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
                                MyToast.show("开始时间不得晚于结束时间");
                                tvRentTime.setText("");
                            } else {
                                tvRentTime.setText(mYear + "-" + monthS + "-" + dayS);
                            }
                        } else {
                            tvRentTime.setText(mYear + "-" + monthS + "-" + dayS);
                        }
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDay(0);
    }

    int mYear2 = 0, mMonth2 = 0, mDay2 = 0;
    String dayS2 = "", monthS2 = "";

    private void showDatePickEndDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        if (mDay2 == 0) {
            mYear2 = calendar.get(Calendar.YEAR);
            mMonth2 = calendar.get(Calendar.MONTH);
            mDay2 = calendar.get(Calendar.DAY_OF_MONTH);
        }
        BasisTimesUtils.showDatePickerDialog(this, true, "请选择日期", mYear2, mMonth2, mDay2,
                new BasisTimesUtils.OnDatePickerListener() {

                    @Override
                    public void onConfirm(int year, int month, int dayOfMonth) {
                        mYear2 = year;
                        mMonth2 = month - 1;
                        mDay2 = dayOfMonth;
                        if (dayOfMonth > 9) {
                            dayS2 = dayOfMonth + "";
                        } else {
                            dayS2 = "0" + dayOfMonth;
                        }
                        if (month > 9) {
                            monthS2 = month + "";
                        } else {
                            monthS2 = "0" + month;
                        }
                        if (!Utils.isNull(tvRentTime.getText().toString())) {
                            if (Utils.getTimeCompareSize(mYear + "-" + monthS + "-" + dayS,
                                    mYear2 + "-" + monthS2 + "-" + dayS2) == 1) {
                                MyToast.show("结束时间不能早于开始时间");
                                tvRentEndTime.setText("");
                            } else {
                                tvRentEndTime.setText(mYear2 + "-" + monthS2 + "-" + dayS2);
                            }
                        } else {
                            tvRentEndTime.setText(mYear2 + "-" + monthS2 + "-" + dayS2);
                        }
                    }

                    @Override
                    public void onCancel() {
                    }
                }).setDay(0);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                if (encryptStatus) {
                    for (int i = 0; i < filesList.size(); i++) {
                        for (int j = 0; j < filesList.get(i).getDatabase().size(); j++) {
                            if (filesList.get(i).getDatabase().get(j).getDataCode().equals(recevierDataCode)) {
                                if (!filesList.get(i).getDatabase().get(j).isOpen()) {
                                    if (encryptStatus) {
                                        filesList.get(i).getDatabase().get(j).setOpen(true);
                                    }
                                    dealData(0, 0, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                                }

                            }
                        }
                    }
                } else {
                    int parent = 0;
                    int child = 0;
                    String datas = position + "";
                    if (datas.length() > 1) {
                        parent = Utils.changeNumber(datas.substring(0, 1));
                        child = Utils.changeNumber(datas.substring(1, 2));
                    }
                    for (int i = 0; i < filesList.get(parent).getDatabase().size(); i++) {
                        if (filesList.get(parent).getDatabase().get(i).getDataCode().equals(recevierDataCode)) {
                            if (!filesList.get(parent).getDatabase().get(i).isOpen()) {
                                if (encryptStatus) {
                                    filesList.get(parent).getDatabase().get(i).setOpen(true);
                                }
                                dealData(parent, child, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                            }

                        }
                    }
                }
            }
        }

    };

    /**
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int parent, int child, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (adapter != null) {
                    filesList.get(parent).getDatabase().get(child).setProgress(percent);
                    adapter.setRefresh(child);
                }
            } else if (percent == 100) {
                if (adapter != null) {
                    filesList.get(parent).getDatabase().get(child).setProgress(100);
                    adapter.setRefresh(child);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(ShopAddActivity.this, fileUrl, fileName, recevierDataCode, tag);
                        }
                    }.start();
                }


            } else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                newIntent.putExtra("secret", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(tag);// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bottomDialog != null) {
            bottomDialog.dismiss();
        }
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (edContent != null) {
            Utils.hideInputKeyboard(this, edContent);
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }
}
